/**
 * @desc 回收站商品列表
 * @author yd_zhaorongjun
 */
<template>
  <div class="gl_contentBox gl_heightFull">
    <div v-if="this.$route.name === 'Recycle'">
      <div class="demo-input-suffix gl_searchBox">
        <el-row style="width:100%">
          <el-col style="width:100%">
            <div class="buJu">
              <div class="headerLeft" style="width:120px">
                <p>商品分组</p>
                <el-select v-model="value" placeholder="请选择" size="mini" @change="check()">
                  <el-option label="全部" value="" />
                  <el-option v-for="item in options" :key="item.description" :label="item.name" :value="item.id" />
                </el-select>
              </div>
              <div class="headerRight">
                <div style="margin-left:20px;width:120px">
                  <p>商品名称:</p>
                  <el-input v-model="goodsName" placeholder="请输入" size="mini" clearable @change="check()" />
                </div>
                <div>
                  <el-row :md="19" :lg="21" :xl="21" style="text-align:right">
                    <!-- 查询按钮 -->
                    <el-button style="margin-top: 27px; margin-left:30px" type="primary" size="mini" @click="check()">
                      {{ $t("button.query") }}
                    </el-button>
                    <!-- 重置按钮 -->
                    <el-button style="margin-top: 27px; margin-left: 20px" type="warning" size="mini" @click="refreshSearchForm">
                      {{ $t("button.Reset") }}
                    </el-button>
                  </el-row>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <div style="margin-top:10px">
        <el-button type="primary" size="mini" @click="moreRemove">批量永久删除</el-button>
        <el-button type="primary" size="mini" @click="moreRestore">批量恢复</el-button>
        <div>
          <el-table ref="tableData" v-loading="tableLoading" :data="tableData" class="gl_table_noBorder" size="mini" style="width: 100%; margin-top: 10px" @sort-change="sortChange" @selection-change="selection">
            <el-table-column type="selection" label-class-name="selection" width="55" />
            <el-table-column label="序号" type="index" align="center" width="55" />
            <el-table-column label="商品信息" width="70">
              <template slot-scope="{ row }">
                <div class="gl_clear gl_my_5">
                  <div class="gl_mr_10 gl_fl" style="height: 60px">
                    <img style="height: 90%" class="table_photo" :src="getStaticFileUrl(row.images[0].imageUrl)" alt="" @error="errorPhoto" @mouseenter="showGoodsImg(...arguments, row.images[0].imageUrl)" @mouseleave="hideGoodsImg(row.images[0].imageUrl)">
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="" min-width="350" />
            <el-table-column label="价格" sortable="custom">
              <template slot-scope="{ row }">
                {{ row.price || row.price === 0 ? '￥' + row.price/100 : '--' }}
              </template>
            </el-table-column>
            <el-table-column prop="count" label="库存" sortable="custom" />
            <el-table-column prop="group.name" label="所属分组" />
            <el-table-column prop="creatorName" label="创建人" />
            <el-table-column prop="creationTime" label="创建时间">
              <template slot-scope="{ row }">
                <span>
                  {{ row.creationTime | FormatDate("yyyy-MM-dd HH:mm:ss") }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="226px">
              <template slot-scope="scope">
                <div class="handle">
                  <el-button type="text" size="mini" style="color: #1990ff" @click="editor(scope.$index)">
                    编辑
                  </el-button>
                  <el-button type="text" size="mini" style="color: #1990ff" @click="restore(scope.$index)">
                    恢复
                  </el-button>
                  <el-button type="text" size="mini" style="color: #ff3434" @click="remove(scope.$index)">
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <img v-if="isShowImg && getStaticFileUrl(bigImg)" class="roodsBigPhoto" :style="position" :src="getStaticFileUrl(bigImg)" alt="" @error="errorPhoto">
        </div>
        <el-row class="gl_pt_20" style="text-align: right">
          <el-pagination :current-page="Api_GET_MallProductQO.Page" :page-size="Api_GET_MallProductQO.MaxResultCount" :total="totalPage" layout="total,sizes,prev,pager,next,jumper" :page-sizes="[10, 20, 30, 40]" @size-change="sizeChange" @current-change="pageIndexChange" />
        </el-row>
      </div>
    </div>
    <router-view />
    <restore ref="restore" :store-id="storeId" @statuscode="fathercode" />
  </div>
</template>
<script>
import restore from './restore.vue';
import { mapState, mapActions } from 'vuex';
import defaultImg from '@/assets/images/face_default.png';
import {
  Api_GET_MallProductGroupQO,
  Api_GET_MallProductQO,
  Api_PUT_MallProductIdStatusQO,
  Api_PUT_MallProductStatusListQO,
  Api_DELETE_MallProductListQO
} from '@/lib/form/shoppingmall/swaggerForm';
import {
  api_GET_MallProductGroup,
  api_GET_MallStoreCurrent,
  api_GET_MallProduct,
  api_DELETE_MallProductId,
  api_PUT_MallProductIdStatus,
  api_PUT_MallProductStatusList,
  api_DELETE_MallProductList
} from '@/extend/api/shoppingmallswaggerApi/app';
// import { concat } from 'mock/user';
export default {
  components: { restore },
  data() {
    return {
      defaultImg: defaultImg,
      Api_DELETE_MallProductListQO: new Api_DELETE_MallProductListQO(), // 批量删除
      Api_PUT_MallProductStatusListQO: new Api_PUT_MallProductStatusListQO(), // 批量商品状态
      Api_PUT_MallProductIdStatusQO: new Api_PUT_MallProductIdStatusQO(), // 商品状态
      totalPage: 0,
      Api_GET_MallProductQO: new Api_GET_MallProductQO(),
      tableData: [],
      tableLoading: false,
      storeId: '',
      options: [],
      Api_GET_MallProductGroupQO: new Api_GET_MallProductGroupQO(),
      value: '', // 获取下拉列表值
      goodsName: '',
      Code: '', // 判断批量恢复或单恢复
      selectData: [], // 选中的数据
      isShowImg: false,
      position: {
        left: 0,
        top: 0
      },
      bigImg: ''
    };
  },
  computed: {
    ...mapState({
      dictAll: (state) => state.dict.dictAll
    })
  },
  watch: {
    storeId: {
      handler: function (val) {
        if (!val) return;
        this.refreshList();
      }
    }
  },
  created() {
    this.api_GET_MallStoreCurrent();
    this.getDict();
  },
  methods: {
    ...mapActions({
      getCurrentUserType: 'user/getCurrentUserType',
      getDict: 'dict/getDict',
      getDictByType: 'dict/getDictByType'
    }),
    // 获取静态图片
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) {
        console.log(relativeUrl);
      } else {
        return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
      }
    },
    showGoodsImg(event, img) {
      const _this = this;
      _this.bigImg = img;
      const _img = event.target; // 这里就是获取到的dom元素
      const _position = _img.getBoundingClientRect();
      this.timeOut = setTimeout(() => {
        _this.isShowImg = true;
        _this.$set(_this.position, 'left', _position.left + 60 + 'px');
        _this.$set(_this.position, 'top', _position.top + 'px');
      }, 300);
    },
    hideGoodsImg() {
      const _this = this;
      clearTimeout(this.timeOut);
      _this.isShowImg = false;
    },
    errorPhoto() {
      const img = event.srcElement;
      img.src = this.defaultImg;
    },
    // 获取当前用户店铺信息
    api_GET_MallStoreCurrent() {
      api_GET_MallStoreCurrent({ IncludeStatus: true }).then(
        (res) => {
          this.storeId = res.id || '';
        },
        (error) => {
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        }
      );
    },
    // 获取下拉列表
    refreshList(page) {
      this.tableLoading = true;
      this.Api_GET_MallProductQO.Page = page || 1;
      this.Api_GET_MallProductQO.SkipCount = (this.Api_GET_MallProductQO.Page - 1) * this.Api_GET_MallProductQO.MaxResultCount;
      this.Api_GET_MallProductQO.StoreId = this.storeId;
      this.Api_GET_MallProductQO.IncludeImages = true;
      this.Api_GET_MallProductQO.IncludeGroup = true;
      this.Api_GET_MallProductQO.IncludeColors = true;
      this.Api_GET_MallProductQO.IncludeSizes = true;
      this.Api_GET_MallProductQO.IsRecommended = null;
      this.Api_GET_MallProductQO.IncludeInventories = true;
      this.Api_GET_MallProductQO.properties = true;
      this.Api_GET_MallProductQO.MinPrice = null;
      this.Api_GET_MallProductQO.MaxPrice = null;
      this.Api_GET_MallProductQO.MinCount = null;
      this.Api_GET_MallProductQO.MaxCount = null;
      this.Api_GET_MallProductGroupQO.StoreId = this.storeId;
      this.Api_GET_MallProductQO.ProductStatusCodes[0] = 'Deleted';
      this.Api_GET_MallProductQO.Sorting = this.Api_GET_MallProductQO.Sorting || 'creationTime DESC';
      api_GET_MallProductGroup(this.Api_GET_MallProductGroupQO).then(
        (res) => {
          this.options = res.items;
        },
        (error) => {
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        }
      );
      // 获取商品列表;
      api_GET_MallProduct(this.Api_GET_MallProductQO).then(
        (res) => {
          this.tableData = res.items;
          this.totalPage = res.totalCount;
          this.tableLoading = false;
          console.log(res);
        },
        (error) => {
          this.tableLoading = false;
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        }
      );
    },
    // 选中的数据
    selection(val) {
      this.selectData = [];
      if (val.length > 0) {
        val.forEach(item => {
          this.selectData.push(item.id);
        });
      }
    },
    restore(index) {
      this.tableData = this.$refs.tableData.tableData;
      this.Code = index;
      this.$refs.restore.loading = true;
      this.$refs.restore.dialogVisible = true;
    },
    remove(index) {
      this.tableData = this.$refs.tableData.tableData;
      const _this = this;
      this.$confirm(`您确定要删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api_DELETE_MallProductId(this.tableData[index].id).then(
          (res) => {
            this.$message({ type: 'success', message: '删除成功' });
            _this.refreshList(this.Api_GET_MallProductQO.Page);
          }, (error) => {
            const _msg = error.error.message || error.message;
            this.$message({ type: 'error', message: _msg });
          }
        );
      }).catch(() => {});
    },
    sizeChange(MaxResultCount) {
      this.Api_GET_MallProductQO.MaxResultCount = MaxResultCount;
      this.refreshList();
    },
    pageIndexChange(currentPage) {
      this.refreshList(currentPage);
    },
    // 查询按钮
    check() {
      this.Api_GET_MallProductQO.ProductGroupId = this.value;
      this.Api_GET_MallProductQO.Filter = this.goodsName;
      this.refreshList();
    },
    // 重置按钮
    refreshSearchForm() {
      this.value = '';
      this.goodsName = '';
      this.Api_GET_MallProductQO = new Api_GET_MallProductQO();
      this.refreshList();
    },
    // 编辑按钮
    editor(index) {
      this.tableData = this.$refs.tableData.tableData;
      const _name = 'EditRecycle';
      const _id = this.tableData[index].id;
      this.$router.push({
        name: _name,
        params: { id: _id }
      });
    },
    // 批量恢复
    moreRestore() {
      if (this.selectData.length === 0) {
        this.$message({
          message: '请选择商品',
          type: 'warning'
        });
        return;
      }
      this.$refs.restore.loading = true;
      this.$refs.restore.dialogVisible = true;
    },
    // 批量删除
    moreRemove() {
      const _this = this;
      this.Api_DELETE_MallProductListQO.ids = this.selectData;
      if (this.selectData.length === 0) {
        this.$message({
          message: '请选择商品',
          type: 'warning'
        });
        return;
      }
      this.$confirm(`您确定要删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          api_DELETE_MallProductList(this.Api_DELETE_MallProductListQO).then(
            (res) => {
              this.$message({ type: 'success', message: '删除成功' });
              _this.refreshList(this.Api_GET_MallProductQO.Page);
            },
            (error) => {
              const _msg = error.error.message || error.message;
              this.$message({ type: 'error', message: _msg });
            }
          );
        })
        .catch(() => {});
    },
    // 批量恢复、恢复
    fathercode(val) {
      const _this = this;
      const flg = this.Code === '';
      if (!flg) {
        this.Api_PUT_MallProductIdStatusQO.statusCode = val;
        this.$confirm(`您确定要恢复吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          api_PUT_MallProductIdStatus(
            this.tableData[this.Code].id,
            this.Api_PUT_MallProductIdStatusQO
          ).then((res) => {
            this.$message({ type: 'success', message: '恢复成功' });
            _this.refreshList(this.Api_GET_MallProductQO.Page);
            this.Code = '';
          }, (error) => {
            const _msg = error.error.message || error.message;
            this.$message({ type: 'error', message: _msg });
          }
          );
        }).catch(() => {});
      } else {
        this.Api_PUT_MallProductStatusListQO.statusCode = val;
        const _this = this;
        this.$confirm(`您确定要恢复吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          api_PUT_MallProductStatusList(
            this.Api_PUT_MallProductStatusListQO,
            this.selectData
          ).then(
            (res) => {
              this.$message({ type: 'success', message: '恢复成功' });
              _this.refreshList(this.Api_GET_MallProductQO.Page);
            },
            (error) => {
              const _msg = error.error.message || error.message;
              this.$message({ type: 'error', message: _msg });
            }
          );
        }).catch(() => {});
      }
    },
    // 价格、库存排序
    sortChange (val) {
      console.log(val);
      // 升序："Price"，倒序："Price DESC"
      if (val.column.label === '价格' && val.order === 'ascending') {
        this.Api_GET_MallProductQO.Sorting = 'Price';
      } else if (val.column.label === '价格' && val.order === 'descending') {
        this.Api_GET_MallProductQO.Sorting = 'Price DESC';
      } else if (val.column.label === '库存' && val.order === 'ascending') {
        this.Api_GET_MallProductQO.Sorting = 'count';
      } else if (val.column.label === '库存' && val.order === 'descending') {
        this.Api_GET_MallProductQO.Sorting = 'count DESC';
      } else {
        this.Api_GET_MallProductQO.Sorting = '';
      }
      this.refreshList(this.Api_GET_MallProductQO.Page);
    }
  }
};
</script>
<style scoped>
.el-col-lg-3 {
  width: 600px;
}
.buJu {
  width: 100%;
  display: flex;
}
.headerLeft {
  width: 100px;
}
.headerRight {
  flex: 1;
  display: flex;
  justify-content: space-between;
}
.el-input__inner {
  height: 28px;
  line-height: 28px;
}
.roodsBigPhoto {
  width: 310px;
  height: 280px;
  position: fixed;
  z-index: 10;
}
</style>
